<template>
  <!-- 这个组件不需要渲染任何内容，只负责监控会话状态 -->
</template>

<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue';
import { useRouter } from 'vue-router';
import { sessionManager } from '@/utils/session';
import { SessionStatus } from '@/config/session';
import { ElMessage } from 'element-plus';

const router = useRouter();

// 会话过期处理
const handleSessionExpired = () => {
  ElMessage.error('会话已过期，请重新登录');
  router.push('/login');
};

// 会话警告处理
const handleSessionWarning = () => {
  const remainingTime = Math.ceil(sessionManager.getRemainingTime());
  ElMessage.warning(`会话将在 ${remainingTime} 分钟后过期，请及时操作`);
};

// 用户活动监听
const handleUserActivity = () => {
  // 用户有活动时刷新会话
  if (sessionManager.isLoggedIn()) {
    sessionManager.refreshSession();
  }
};

onMounted(() => {
  // 检查是否已登录
  if (sessionManager.isLoggedIn()) {
    // 检查当前会话状态
    const status = sessionManager.checkSessionStatus();
    
    if (status === SessionStatus.EXPIRED) {
      handleSessionExpired();
      return;
    }
    
    // 开始会话监控
    sessionManager.startMonitoring(handleSessionExpired, handleSessionWarning);
    
    // 监听用户活动
    const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
    events.forEach(event => {
      document.addEventListener(event, handleUserActivity, true);
    });
  }
});

onUnmounted(() => {
  // 停止会话监控
  sessionManager.stopMonitoring();
  
  // 移除事件监听
  const events = ['mousedown', 'mousemove', 'keypress', 'scroll', 'touchstart'];
  events.forEach(event => {
    document.removeEventListener(event, handleUserActivity, true);
  });
});
</script> 